package edu.mbb.cloud.nacos;

import edu.mbb.cloud.nacos.listen.ClientWorker;
import edu.mbb.cloud.nacos.listen.MD5;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.*;

public class SimpleHttpUtil {


    public static String methodGet(String urlStr) {
        //ConstatFinalUtil.SYS_LOGGER.info("--methodGet--url:{}",urlStr);
        String result = "";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();


            /* 获取网址对应的输入流和输出流 */

            InputStream is = connection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));


            String line = "";
            while ((line = br.readLine()) != null) {
                result += line;
                result += "\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.substring(0, result.lastIndexOf("\n"));
    }


    public static void main(String[] args) {
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Long-Pulling-Timeout", "4500");
        headMap.put(" Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        String aa = "Listening-Configs=nacos-config-client-dev.yaml%02TEST_GROUP%02aa48fd1ba24398d540925d9843470722%02b8b51e18-7395-4124-8840-fe39fde231b1%01nacos-config-client.yaml%02TEST_GROUP%02a9d26e4b7c8ab5043dd9c0fb2214bf1c%02b8b51e18-7395-4124-8840-fe39fde231b1%01";
        String ss = "Listening-Configs=nacos-config-client-dev.yaml%02TEST_GROUP%024706e98b2d9447ddc23dee45b3d01d01%02b8b51e18-7395-4124-8840-fe39fde231b1%01nacos-config-client.yaml%02TEST_GROUP%02a9d26e4b7c8ab5043dd9c0fb2214bf1c%02b8b51e18-7395-4124-8840-fe39fde231b1%01";
        System.out.println(aa);
        System.out.println(ss);
        String s = methodPost("http://localhost:8848/nacos/v1/cs/configs/listener", headMap, aa);
        System.out.println(s);
    }

    public static String methodPost(String uri, Map<String, String> headerMap,
                                    String params) {
        //如果是https协议
        StringBuilder sb=new StringBuilder();
        // 连续请求多次
        for (int i = 0; i < 3; i++) {
            HttpURLConnection connect = null;
            try {
                URL url = new URL(uri);
                connect = (HttpURLConnection) url
                        .openConnection();
                connect.setConnectTimeout(3000);
                connect.setReadTimeout(3000);
                connect.setDoInput(true);
                connect.setDoOutput(true);


                connect.setRequestProperty(
                        "exConfigInfo",
                        "true");
                connect.setRequestProperty("RequestId",
                        UUID.randomUUID().toString().replace("-", ""));
                connect.setRequestProperty("Client-Version",
                        "203");
                connect.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded;charset=UTF-8");
                connect.setRequestProperty("Client-AppName",
                        "unknown");
                String ts = String.valueOf(System.currentTimeMillis());
                String token = MD5.getInstance().getMD5String(ts + "");
                connect.setRequestProperty("Client-RequestTS",
                        "ts");
                connect.setRequestProperty("Client-RequestToken",
                        token);
               /* for (Iterator iterator = headerMap.entrySet().iterator(); iterator
                        .hasNext();)
                {
                    Map.Entry me = (Map.Entry) iterator.next();
                    connect.setRequestProperty(me.getKey() + "", me.getValue() + "");
                }*/


                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                        connect.getOutputStream()));
                bw.write(params);
                bw.flush();

                //响应码成功
                    Map<String, List<String>> headerFields = connect.getHeaderFields();
                    System.out.println(headerFields);
                    //出现变动的key
                    List<String> probeModifyResponse = headerFields.get("Probe-Modify-Response");
                    //带有nameSpace
                    List<String> probeModifyResponseNew = headerFields.get("Probe-Modify-Response-New");
                    if(!CollectionUtils.isEmpty(probeModifyResponseNew)) {
                        for (String s : probeModifyResponseNew) {
                            sb.append(s);
                            sb.append(ClientWorker.LINE_SEPARATOR);
                        }
                    }
                    System.out.println(probeModifyResponseNew);
                bw.close();
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
            //重试机制
            if (!"true".equalsIgnoreCase(headerMap.get("retry"))) {
                break;
            }
        }
        return sb.toString();
    }


}
